<?php
	function verifyCsrfToken(){
		return (isset($_POST['token']) && $_POST['token'] === $_SESSION['token']);
	}
	function csrfField(){
		return '<div style="display:none;"><input type="hidden"  name="token" value="'.$_SESSION['token'].'" /></div>';
	}
	
	/// returns the POST value if set and not empty, else returns the default value
	function postOrCustom($postKey, $ifEmptyValue=''){
		if(isset($_POST[$postKey]) && (!empty($_POST[$postKey]) || $_POST[$postKey]==='0') )
			return $_POST[$postKey];
		else
			return $ifEmptyValue;
	}
	
	/// returns the GET value if set and not empty, else returns the default value
	function getOrCustom($getKey, $ifEmptyValue=''){
		if(isset($_GET[$getKey]) && (!empty($_GET[$getKey]) || $_GET[$getKey]==='0') )
			return $_GET[$getKey];
		else
			return $ifEmptyValue;
	}
		
	function issetOrDefault($array, $key, $default){
		if(isset($array[$key])){
			return $array[$key];
		}
		else
			return $default;
	}
	
	function emailIsValid($email){
		return filter_var($email, FILTER_VALIDATE_EMAIL);
	}
	
	function urlIsValid($email){
		return filter_var($email, FILTER_VALIDATE_URL);
	}
	
	function checkRights($level){
		if(isset($_SESSION["user"]))
		{
			if($_SESSION["user"]->getState() == NORMAL)
			{
				if($_SESSION["user"]->getAdmin_level() == $level)
				{
					return true;
				}
			}
		}
		return false;
	}
	
	function unix_timestamp($date)
	{
		/// http://pioupioum.fr/snippets/php-convertir-datetime-unix-timestamp.html
		$date = str_replace(array(' ', ':'), '-', $date);
		$c    = explode('-', $date);
		$c    = array_pad($c, 6, 0);
		array_walk($c, 'intval');
	 
		return mktime($c[3], $c[4], $c[5], $c[1], $c[2], $c[0]);
	}
	
	function randomString($car) {
		$string = "";
		$chaine = "abcdefghijklmnpqrstuvwxy0123456789_AZERTYUIOPQSDFGHJKLMWXCVBN";
		srand((double)microtime()*1000000);
		for($i=0; $i<$car; $i++) {
			$string .= $chaine[rand()%strlen($chaine)];
		}
		return $string;
	}